<template>
    <v-dialog v-model="dialogFormVisible" max-width="800px" persistent scrollable>
        <v-card class="elevation-10 pa-2">
            <v-card-title class="d-flex align-center">
                Edit
            </v-card-title>

            <v-card-text>
                <v-form ref="formRef" v-model="formValid">
                    <v-row>
                        <v-col cols="12" md="6">
                            <v-text-field v-model="form.title" label="节点名称"
                                          variant="outlined" density="compact" :rules="rules.title"
                            required hide-details="auto" />
                        </v-col>

                        <v-col cols="12" md="6">
                            <v-text-field type="number" v-model="form.sort" label="排序"
                                          variant="outlined" density="compact" :rules="rules.sort"
                            required hide-details="auto" />
                        </v-col>

                        <v-col cols="12" md="6">
                            <v-text-field v-model="form.type" label="节点类型" :disabled="true"
                                          variant="outlined" density="compact" :rules="rules.type"
                            required hide-details="auto" />
                        </v-col>

                        <v-col cols="12" md="6">
                            <!-- 单选 -->
                             <!-- {{ form.roleType }} -->
                            <v-radio-group v-model="form.roleType" :rules="rules.roleType" label="角色类型" class="d-flex ">
                                <v-radio label="个人" :value="1"></v-radio>
                                <v-radio label="角色" :value="2"></v-radio>
                            </v-radio-group>
                        </v-col>
                        <v-col cols="12" md="6">

                            <!-- 对象是用户 -->
                            <SelectUser v-if="form.roleType==1" v-model="selectedAssignedUser" label="用户"
                                                        hide-details="auto" placeholder="可多选" variant="outlined"
                                                        density="comfortable"
                                                        :multiple="true"
                                                        prepend-inner-icon="mdi-account-arrow-right"
                                                        @user-selected-list="handleAssignedUserSelect" class="mb-3" />
                            <!-- 对象是角色 -->
                            <SelectRole v-if="form.roleType==2" v-model="selectedAssignedRole" label="角色"
                                                        hide-details="auto" placeholder="可多选" variant="outlined"
                                                        density="comfortable"
                                                        prepend-inner-icon="mdi-account-arrow-right"
                                                        @user-selected="handleAssignedUserSelect" class="mb-3" />
                            <!-- <v-text-field v-model="form.ids" label="ids"
                                          variant="outlined" density="compact" :rules="rules.ids"
                            required hide-details="auto" /> -->
                        </v-col>
                        <!-- (adn-or) -->
                        <v-col cols="12" md="6">
                            <!-- 单选 -->
                            <v-radio-group v-model="form.andOr" :rules="rules.andOr" label="与或" class="d-flex color-primary">
                                <v-radio label="与" value="and"></v-radio>
                                <v-radio label="或" value="or"></v-radio>
                            </v-radio-group>
                            <!-- 提示 -->
                             <div class="d-flex align-center gap-2 mt-2 text-caption text-grey-darken-1">
                                <v-icon size="16" color="info">mdi-information-outline</v-icon>
                                <span>与:必须都同意,或:只要有一个同意即可</span>
                             </div>
                        </v-col>
                        <v-col cols="12" md="6">

                            <!-- 对象是用户 -->
                            <SelectUser  v-model="selectedCopiedTo" label="抄送人"
                                                        hide-details="auto" placeholder="可多选" variant="outlined"
                                                        density="comfortable"
                                                        :multiple="true"
                                                        prepend-inner-icon="mdi-account-arrow-right"
                                                        @user-selected-list="handleCopiedToSelect" class="mb-3" />
                          
                        </v-col>
                        <v-col cols="12" md="6">
                            <v-text-field v-model="form.remark" label="备注"
                                          variant="outlined" density="compact" :rules="rules.remark"
hide-details="auto" />
                        </v-col>
                       
                    </v-row>
                </v-form>
            </v-card-text>

            <v-card-actions>
                <v-spacer />
                <v-btn color="grey-darken-1" variant="text" @click="close">
                    Cancel
                </v-btn>
                <v-btn color="primary" variant="text" :loading="saving" @click="save">
                    Confirm
                </v-btn>
            </v-card-actions>
        </v-card>
    </v-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, nextTick, onMounted } from 'vue';
import {
    doInsert,
    doUpdate,
    type ApprovalNodeModel,
    type ApiResponse
} from '@/api/approval/node/ApprovalNodeManagementApi';
import { isNull } from '@/utils/validate';
import { formateDate } from '@/utils/format';
import SelectUser from '@/components/SelectUser.vue';
import SelectRole from '@/components/SelectRole.vue';
import { validatorRule } from '@/utils/validateRule';
import type { UserInfo } from '@/components/SelectUser.vue';
import type { RoleInfo } from '@/components/SelectRole.vue';
import { getDictListSync } from '@/utils/dict';
import { useMessage } from '@/composables/useMessage';

const { success: showSuccess, error: showError } = useMessage();

const props = defineProps<{
    type: string;
}>();
// 基础数据
const dialogFormVisible = ref(false);
const title = ref('');
const formValid = ref(false);
const formRef = ref();
const saving = ref(false);
const selectedAssignedUser = ref<UserInfo[]>([]);
const selectedAssignedRole = ref<RoleInfo | null>(null);
const selectedCopiedTo = ref<UserInfo[]>([]);

/**
 * 用户
 * @param users 用户
 */
const handleAssignedUserSelect = (users: UserInfo[]) => {
    console.log('handleAssignedUserSelect', users);
    form.ids = users.map(user => user.id).join(',');
    console.log('form.ids', form.ids);

}
/**
 * 角色
 * @param role 角色
 */
const handleAssignedRoleSelect = (role: RoleInfo | null) => {
    console.log('handleAssignedRoleSelect', role);
    form.ids = role.id;
}

/**
 * 抄送人
 * @param users 抄送人
 */
const handleCopiedToSelect = (users: UserInfo[]) => {
    console.log('handleCopiedToSelect', users);
    form.copiedTo = users.map(user => user.id).join(',');
}


const defaultFrom:ApprovalNodeModel = {
    title: '',
    type: props.type,
    roleType: 1,
    sort: 0,
    ids: '',
    remark: '',
    andOr: 'and',
    copiedTo: '',
}

// 表单数据
const form = reactive < Partial <ApprovalNodeModel>> (defaultFrom);

// 字典数据
const dict = reactive({
});

// 验证规则
const rules = {

sort: [
(v: any) => !!v || '排序不能为空',
],
title: [
(v: any) => !!v || '节点名称不能为空',
],
andOr: [
(v: any) => !!v || '节点类型不能为空',
],
type: [
(v: any) => !!v || '节点类型(adn-or)不能为空',
],
roleType: [
(v: any) => !!v || '角色类型(1个人2 角色)不能为空',
],
ids: [
(v: any) => !!v || 'ids不能为空',
],
remark: [],
};

const roleTypeItems = [
    { title: '个人', value: 1 },
    { title: '角色', value: 2 },
];


// 事件发射
const emit = defineEmits<{
    fetchData: [];
    type: [string];
}>();

// 显示编辑对话框
function showEdit(row?: ApprovalNodeModel) {
    if (!row) {
        title.value = '添加审批节点';
        // 重置表单为默认值
        Object.assign(form, defaultFrom);
    } else {
        title.value = '编辑审批节点';
        // 复制行数据到表单，处理日期格式
        const formData = { ...row };

        if (formData.ids) {
            selectedAssignedUser.value = formData.ids.split(',').map(id => ({ id: id, realName: '', email: '', avatar: '' }));
        }
        if (formData.copiedTo) {
            selectedCopiedTo.value = formData.copiedTo.split(',').map(id => ({ id: id, realName: '', email: '', avatar: '' }));
        }


        Object.assign(form, formData);
    }

    dialogFormVisible.value = true;
}

// 关闭对话框
function close() {
    dialogFormVisible.value = false;
    nextTick(() => {
        if (formRef.value) {
            formRef.value.reset();
        }
        // 重置表单数据
        Object.assign(form, defaultFrom);
    });
}

// 保存
async function save() {
    if (!formRef.value) return;

    try {
        const { valid } = await formRef.value.validate();
        if (!valid) return;

        saving.value = true;

        // 处理表单数据
        const submitData = { ...form } as ApprovalNodeModel;
        handlerFormData(submitData);

        let response: ApiResponse<ApprovalNodeModel >;

        // 编辑模式
        if (!isNull(submitData.id)) {
            let {msg} = await doUpdate(submitData);
            showSuccess(msg || 'update success');
        } else {
            // 新增模式
             let {msg}  = await doInsert(submitData);
            showSuccess(msg || 'add success');
        }

        // 通知父组件刷新数据
        emit('fetchData');
        close();
    } catch (error) {
        console.error('save failed:', error);
        showError('save failed');
    } finally {
        saving.value = false;
    }
}

// 处理表单数据
function handlerFormData(formData: any) {
    if (!isNull(formData)) {
        for (const key in formData) {
            // 对于时间类进行处理
            if (Object.prototype.toString.call(formData[key]) === '[object Date]') {
                formData[key] = formateDate(formData[key], 'yyyy-MM-dd hh:mm:ss');
            }
            // 处理datetime-local格式
            else if (typeof formData[key] === 'string' && formData[key].includes('T')) {
                formData[key] = formData[key].replace('T', ' ') + ':00';
            }
        }
    }
}

// 初始化字典数据
function initDict() {
}

// 暴露方法
defineExpose({
    showEdit,
});

// 生命周期
onMounted(() => {
    initDict();
});
</script>

<style lang="scss" scoped>
:deep(.v-selection-control-group){
    display: flex;
    gap: 8px;
    flex-direction: row !important;
}
:deep(.v-dialog) {
    .v-card-title {
        background-color: rgb(var(--v-theme-primary));
        color: white;
    }
}
</style>